package post_to_in_pkg.node;

import post_to_in_pkg.GlobalConfig;
import post_to_in_pkg.lexer.Tag;
import post_to_in_pkg.lexer.Token;
import post_to_in_pkg.parser.Type;

public class TempNode extends OperandNode{
	
	static int temp_var_count=1;
	static final String prefix_of_tempvar="tempVar";
	OperatorNode Operand;
	public TempNode(OperatorNode agr_node) {
		super(
				new Token(prefix_of_tempvar+String.valueOf(temp_var_count++),Tag.TEMP)
				,
				Type.TEMPVAR
			  );
		Operand=agr_node;
	}
	
	static public int getTempVarCount() {
		return temp_var_count;
	}
	
	public boolean isTempNode() {
		return true;
	}
	
	public String toString() {
		String s="\n";
		s=s+"temp "+this.getName()+"="+Operand.toString();
		return s;
	}
	
	public boolean hasChild() {
		if(Operand.hasChild())
			return true;
		else
			return false;			
	}
	
//	public void printChild(StringBuffer content) {
//		if(hasChild()) {
//			StringBuffer str_buf=new StringBuffer();
//			Operand.printChild(str_buf);
//			str_buf.append(toString());
//			content=content.insert(0,str_buf);
//		}
//		else {
//			content=content.insert(0,toString());
//		}
//	}

	public String[] generateCodes(){
		return generateCodes(GlobalConfig.defaultNestLevel);
	}

	public String[] generateCodes(int nestLevel){
		String[] tempStr;
		tempStr=Operand.generateCodes(nestLevel);
//		if(!isReferenced()){
//			if(tempStr[1].startsWith("(")&&tempStr[1].endsWith(")")){
//				tempStr[1]=tempStr[1].substring(1,tempStr[1].length()-1);
//			}
//		}
		if(nestLevel==0){
			//no need to expand
			//strip off the closure () of tempStr
			if(tempStr[1].startsWith("(")&&tempStr[1].endsWith(")")){
				tempStr[1]=tempStr[1].substring(1,tempStr[1].length()-1);
			}
			code[0]=tempStr[0]+"\n"+"auto "+getName()+"="+tempStr[1]+";";
			code[1]=getName();
		}
		else{
			if(isReferenced()){
				code=tempStr;
			}
			else{
				code[0]=tempStr[0];
				code[1]="auto "+getName()+"="+tempStr[1]+";";
			}
		}
		return code;
	}

	static public void resetTempvarCount() {
		temp_var_count=1;
	}
}
